package hn.cch.redis_token.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * redis操作
 */

@Service
public class RedisService {

    // StringRedisTemplate处理字符串的操作
    /*
    RedisTemplate默认使用JdkSerializationRedisSerializer
    会导致插入redis的键值出现乱码前缀导致查询获取删除失败
     */
    @Autowired
    private StringRedisTemplate stringRedisTemplate;



    public void setObject(Object key, Object value){
        ValueOperations valueOperations = stringRedisTemplate.opsForValue();
        valueOperations.set(key, value);
    }

    /**
     * 插入键值并添加过期时间
     * @param key
     * @param value
     * @param timeout
     */
    public void setObjectExpire(Object key, Object value, long timeout){
        ValueOperations valueOperations = stringRedisTemplate.opsForValue();
        valueOperations.set(key, value, timeout, TimeUnit.SECONDS);
    }

    public Object getObject(Object key){
        ValueOperations valueOperations = stringRedisTemplate.opsForValue();
        return valueOperations.get(key);
    }


    /**
     * 检测redis中是否存在键值
     * @param key
     * @return
     */
    public boolean has(String key){
        return stringRedisTemplate.hasKey(key);
    }

    /**
     * 从redis删除键值
     * @param key
     * @return
     */
    public boolean del(String key){
        return stringRedisTemplate.delete(key);
    }



}
